package study.distributed.shardingjdbc.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
public class ShardingDataSourceConfig extends BaseDataSourceConfig {


    @Bean
    public SqlSessionFactory shardSqlSessionFactory(@Qualifier(value = "shardingDataSource")  DataSource dataSource, @Qualifier("shardingConfiguration") org.apache.ibatis.session.Configuration configuration) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setConfiguration(configuration);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/sharding/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    public org.apache.ibatis.session.Configuration shardingConfiguration() {
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        return configuration;
    }

    @Bean(value = SHARDING_TRANSACTION_MANAGER)
    public DataSourceTransactionManager shardingDataSourceTransactionManager(@Qualifier(value = "shardingDataSource")  DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Configuration
    @AutoConfigureAfter(ShardingDataSourceConfig.class)
    public static class MybatisMapperConfiguration{

        @Bean
        public MapperScannerConfigurer shardingMapperScannerConfigurer() {
            MapperScannerConfigurer configurer = new MapperScannerConfigurer();
            configurer.setSqlSessionFactoryBeanName("shardSqlSessionFactory");
            configurer.setBasePackage("study.distributed.shardingjdbc.dao.sharding");
            return configurer;
        }
    }


}
